<template>
  <div class="bgc-white relative" style="height: calc(100vh - 112px); padding-bottom: 65px">
    <div class="ta-center fs16 fw500 p16 border-bottom relative">
      <span>{{ id ? "编辑" : "新增" }}政策</span>
      <div
        class="absolute left-0 top-0 ml16 pointer flex-center"
        style="color: rgba(192, 192, 192, 1); line-height: 58px"
        @click="$router.back()"
      >
        <a-icon type="left" class="fs24 mr8" />
        <span>返回</span>
      </div>
    </div>
    <div
      class="overflow-y-auto"
      :style="{
        margin: '16px auto',
        width: '900px',
        height: isDetail ? 'calc(100vh - 197px)' : 'calc(100vh - 262px)'
      }"
    >
      <div class="title-block">政策信息</div>
      <div class="flex-center flex-wrap">
        <div v-if="groupLst.length > 0" class="flex-center mt24" style="width: 50%">
          <div class="ta-right pr8" style="width: 160px"><span class="pr4" style="color: red">*</span>政策分类：</div>
          <a-select
            v-model="typeCode"
            :disabled="isDetail"
            :options="groupLst"
            placeholder="请选择"
            show-search
            :filterOption="filterOption"
            style="width: 220px"
          />
        </div>
        <div class="flex-center mt24" style="width: 50%">
          <div class="ta-right pr8" style="width: 160px">选择用工单位及分组：</div>
          <a-button :disabled="isDetail" @click="transferVisible = true">已选择 {{ this.targetKeys.length }} 个</a-button>
        </div>
        <div class="flex-center mt24" style="width: 50%">
          <div class="ta-right pr8" style="width: 160px"><span class="pr4" style="color: red">*</span>政策标题：</div>
          <a-input v-model="title" :disabled="isDetail" placeholder="请输入" style="width: 220px" />
        </div>
        <div class="flex-center mt24" style="width: 50%">
          <div class="ta-right pr8" style="width: 160px"><span class="pr4" style="color: red">*</span>政策级别：</div>
          <a-select v-model="policyLevel" :disabled="isDetail" :options="levelOptions" placeholder="请选择政策级别" style="width: 220px" />
        </div>
        <div class="flex-center mt24" style="width: 100%">
          <div class="ta-right pr8 pt4" style="width: 160px; align-self: flex-start">附件上传：</div>
          <a-upload
            :fileList="annex"
            :showUploadList="{ showRemoveIcon: !isDetail }"
            multiple
            action="/file/api/v1/general/upload/attachment"
            name="files"
            @change="onFileChange"
          >
            <a-button :disabled="isDetail"> <a-icon type="upload" />点击上传</a-button>
          </a-upload>
        </div>
      </div>
      <div class="title-block mt24">政策内容</div>
      <div class="p16">
        <div v-if="isDetail" v-html="contentHasStyle" class="editor-preview"></div>
        <VueWangeditor
          v-else
          v-model="contentHasStyle"
          :menus="[
            'head',
            'bold',
            'fontSize',
            'lineHeight',
            'fontName',
            'italic',
            'underline',
            'strikeThrough',
            'foreColor',
            'backColor',
            'justify',
            'image'
          ]"
          class="wangeditor"
          style="z-index: 1; width: 100%"
          @change="onEditorChange"
        />
      </div>
    </div>
    <div v-if="!isDetail" class="p16 ta-right border-top absolute left-0 right-0 bottom-0">
      <a-button type="primary" @click="doSave">确定</a-button>
    </div>
    <a-modal v-model="transferVisible" title="选择分管单位" @ok="onTransferOk" width="800px">
      <a-transfer
        :list-style="{
          width: '320px',
          height: '400px'
        }"
        :operations="['添加', '删除']"
        :dataSource="transferDataSource"
        :targetKeys="targetKeys"
        :showSelectAll="false"
        showSearch
        class="tree-transfer"
        :render="(item) => item.title"
        @change="onTransChange"
        @search="onTransferSearch"
      >
        <template slot="children" slot-scope="{ props: { direction, selectedKeys }, on: { itemSelect } }">
          <a-tree
            v-if="direction === 'left'"
            :treeData="treeData"
            :checkedKeys="[...selectedKeys, ...targetKeys]"
            :replaceFields="replaceFields"
            defaultExpandAll
            blockNode
            checkable
            checkStrictly
            style="height: 300px; overflow-y: scroll"
            @check="
              (_, props) => {
                onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
              }
            "
            @select="
              (_, props) => {
                onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect);
              }
            "
          />
        </template>
      </a-transfer>
    </a-modal>
  </div>
</template>
<script>
import { mapState } from "vuex";
import VueWangeditor from "@/components/ZXR/vueWangeditor";
import { fileListDecode, fileListEncode } from "@/utils/tools";
import { levelOptions } from "./funcs";
import { filterTree } from "@/utils/tools";
export default {
  name: "",
  components: { VueWangeditor },
  mixins: [],
  props: {},
  data() {
    return {
      levelOptions,
      policyLevel: "1",
      typeCode: undefined,
      title: "",
      annex: [],
      content: "",
      contentHasStyle: "",
      groupLst: [],
      targetKeys: [],
      treeData: [],
      transferVisible: false,
      replaceFields: {
        children: "companyList",
        title: "name",
        key: "uuid",
        value: "uuid"
      },
      companyTypeList: []
    };
  },
  computed: {
    ...mapState(["site"]),
    companyTreeWithUuid() {
      return this.site.companyTreeWithUuid;
    },
    companyUuidDictWithInfo() {
      return this.site.companyUuidDictWithInfo;
    },
    cidToUid() {
      const items = Object.values(this.companyUuidDictWithInfo);
      const dict = {};
      for (let i = 0; i < items.length; i++) {
        dict[items[i].id] = items[i].uuid;
      }
      return dict;
    },
    transferDataSource() {
      const newList = Object.values(this.companyUuidDictWithInfo).map((item) => ({
        key: item.uuid,
        title: item.name,
        disabled: item.type === "site"
      }));
      return newList;
    },
    tId() {
      return this.$route.query.tId;
    },
    id() {
      return this.$route.query.id;
    },
    itemDetail() {
      const temp = localStorage.getItem("tempZhengce");
      if (temp) {
        return JSON.parse(temp);
      }
      return null;
    },
    isDetail() {
      return this.$route.path.indexOf("detail") > -1;
    }
  },
  watch: {
    companyUuidDictWithInfo: {
      handler() {
        if (Object.keys(this.companyUuidDictWithInfo).length > 0) {
          const treeDataTemp = filterTree(this.companyTreeWithUuid, "", "companyList", "name");
          if (treeDataTemp[0].type === "site") {
            treeDataTemp[0].disabled = true;
          }
          this.treeData = treeDataTemp;
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.onGroupSearchChange();
    if (!this.id) {
      this.typeCode = this.tId;
    } else {
      this.title = this.itemDetail.title;
      this.typeCode = this.itemDetail.typeCode;
      this.policyLevel = this.itemDetail.policyLevel;
      this.annex = this.itemDetail.annex ? fileListEncode(this.itemDetail.annex) : [];
      this.contentHasStyle = this.itemDetail.contentHasStyle;
      this.content = this.itemDetail.content;
      this.companyTypeList = this.itemDetail.companyTypeList;
      this.targetKeys = this.itemDetail.companyTypeList.map((item) => this.cidToUid[item.id]);
    }
  },
  mounted() {
    localStorage.setItem("tempTypeCode", this.tId);
  },
  methods: {
    onTransferOk() {
      this.companyTypeList = this.targetKeys.map((key) => this.companyUuidDictWithInfo[key]);
      this.transferVisible = false;
    },
    onTransferSearch(dir, val) {
      if (dir === "left") {
        const treeDataTemp = filterTree(this.companyTreeWithUuid, val, "companyList", "name");
        if (treeDataTemp[0].type === "site") {
          treeDataTemp[0].disabled = true;
        }
        this.treeData = treeDataTemp;
      }
    },
    onTransChange(targetKeys) {
      this.targetKeys = targetKeys;
    },
    onChecked(_, e, checkedKeys, itemSelect) {
      const { eventKey } = e.node;
      itemSelect(eventKey, !isChecked(checkedKeys, eventKey));
    },
    doSave() {
      const newValues = {
        typeCode: this.typeCode,
        title: this.title,
        policyLevel: this.policyLevel,
        annex: fileListDecode(this.annex),
        contentHasStyle: this.contentHasStyle,
        content: this.content,
        companyTypeList: this.companyTypeList.filter((item) => !!item)
      };
      if (!this.typeCode || !this.title || !this.policyLevel) {
        this.$message.warning("必须选择分类、级别，并填写标题");
        return false;
      }
      localStorage.setItem("tempTypeCode", this.typeCode);
      if (this.id) {
        this.$request({
          url: `/hr/api/v1/policyCouriers`,
          method: "put",
          data: {
            id: this.id,
            ...newValues
          }
        })
          .then((res) => {
            this.$router.back();
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$request({
          url: `/hr/api/v1/policyCouriers`,
          method: "post",
          data: newValues
        })
          .then((res) => {
            this.$router.back();
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    onEditorChange(html, text) {
      this.contentHasStyle = html;
      this.content = text;
    },
    onFileChange({ file, fileList }) {
      this.annex = fileList;
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    onGroupSearchChange() {
      this.$request({
        url: `/hr/api/v1/policyCourierTypes/listAll`,
        params: {}
      })
        .then((res) => {
          this.groupLst = res.data.map((item) => ({
            label: item.name,
            value: item.code
          }));
        })
        .catch((err) => {
          console.log(err);
        });
    }
  }
};

function isChecked(selectedKeys, eventKey) {
  return selectedKeys.indexOf(eventKey) !== -1;
}
</script>
<style lang="scss" scoped>
.editor-preview {
  ::v-deep img {
    max-width: 100%;
  }
}
</style>
